package com.gaga.console.base.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.gaga.common.enums.CodeEnum;
import com.gaga.common.exception.BusException;
import com.gaga.common.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理器
 *
 * @author yiyi
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler
    public Result busException(BusException e) {
        log.error(e.getMessage());
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler
    @ResponseBody
    public Result notLoginException(NotLoginException e) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        response.setStatus(CodeEnum.NOTLOGIN.getCode());
        return Result.fail(CodeEnum.NOTLOGIN.getCode(), "该用户未登录!");
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public Result noHandleFoundException(NoHandlerFoundException e) {
        log.error(e.getMessage());
        return Result.fail(CodeEnum.NOTFOUND.getCode(), "请求未找到!");
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        // 获取校验失败的详细信息
        BindingResult bindingResult = e.getBindingResult();
        String firstErrorMessage = bindingResult.getFieldErrors().stream()
                .findFirst()
                .map(FieldError::getDefaultMessage)
                .orElse("参数校验失败");

        return Result.fail(CodeEnum.FAIL.getCode(), firstErrorMessage);
    }

    @ExceptionHandler
    @ResponseBody
    public Result unknownException(Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.fail(e.getMessage());
    }

}
